#!/bin/sh
rfc_dir=~/.rfc_cache
rfc=$1
view_cmd=less
if test "x$rfc" = "x"
then
    exit 1;
fi
if test ! -d $rfc_dir
then
    mkdir $rfc_dir 
fi
cd $rfc_dir 


if test -f rfc$rfc.txt 
then
    $view_cmd rfc$rfc.txt
    exit
fi

if test -f norfc$rfc.txt 
then
    echo "Seems no rfc$rfc out there, want to retry?[Y/N]:\c"
    read yes_or_no
    if test "$yes_or_no" != "Y" && test "$yes_or_no" != "y"
    then
        echo Exiting ...
        exit 1
    fi
fi

httpdown () {
    local url
    local curl_exec
    local wget_exec
    local save_path

    url=$1
    echo $url
    save_path=$2
    curl_exec=`which curl`
    if test "z$curl_exec" != "z" && test -x $curl_exec
    then
        $curl_exec --retry 20 -k --compressed -o "$save_path" "$url"
    else
        wget_exec=`which wget`
        if test "z$wget_exec" != "z" && test -x $wget_exec
        then
            $wget_exec --tries=20 --retry-connrefused --no-check-certificate -q -O "$save_path" "$url"
        fi
    fi
}
httpdown "http://www.ietf.org/rfc/rfc$rfc.txt" rfc$rfc.txt

if test ! -f rfc$rfc.txt
then
    echo no rfc$rfc
    touch norfc$rfc.txt
    exit 1
fi
$view_cmd rfc$rfc.txt
